package com.putao.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import com.beust.jcommander.internal.Lists;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.List;

/**
 * @author fuhehuang
 * @email 2628279194@qq.com
 */
@Component
@Slf4j
public class SnowflakeConfig {
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    private long workerId ;                                                         //为终端ID
    private long datacenterId = 1;                                                  //数据中心ID
    private Snowflake snowflake = IdUtil.createSnowflake(workerId,datacenterId);

    @PostConstruct
    public void init(){
        workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
        log.info("当前机器的workId:{}",workerId);
    }

    public synchronized String snowflakeId(){
        return snowflake.nextId() + "";
    }

    public synchronized List<String> getIdBySize(int size){
        List<String> list = Lists.newArrayList();
        if (BigDecimalUtil.biggerThen(BigDecimal.ZERO, BigDecimal.valueOf(size))) {
            return list;
        }
        for (int i = 0; i < size; i++) {
            list.add(snowflake.nextId() + "");
        }
        return list;
    }



    public synchronized long snowflakeId(long workerId,long datacenterId){
        Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId);
        return snowflake.nextId();
    }
}

